#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
配置加载模块
"""

import os
import yaml
from pathlib import Path
from typing import Dict, Any, Optional

from src.utils.logger import get_logger

# 默认配置文件路径
DEFAULT_CONFIG_PATH = Path("./config/config.yaml")

# 默认配置
DEFAULT_CONFIG = {
    "windows": {
        "signatures": ["win32", "dotnet", "electron"],
        "file_extensions": [".exe", ".dll", ".msix"],
    },
    "macos": {
        "signatures": ["macos", "cocoa", "swift", "objc"],
        "file_extensions": [".app", ".dmg", ".framework"],
    },
    "linux": {
        "signatures": ["linux", "gtk", "qt", "elf"],
        "file_extensions": [".so", ".deb", ".rpm", ".appimage"],
    },
    "android": {
        "signatures": ["android", "kotlin", "java"],
        "file_extensions": [".apk", ".aab", ".dex"],
    },
    "ios": {
        "signatures": ["ios", "swift", "objc"],
        "file_extensions": [".ipa", ".app", ".framework"],
    },
    "harmony": {
        "signatures": ["harmony", "ark", "ets"],
        "file_extensions": [".hap", ".app"],
    },
    "report": {
        "formats": ["html", "json", "pdf"],
        "template_dir": "./templates",
    }
}

logger = get_logger("config")

def load_config(config_path: Optional[str] = None) -> Dict[str, Any]:
    """
    加载配置文件
    
    Args:
        config_path: 配置文件路径，如果为None则使用默认路径
    
    Returns:
        配置信息字典
    """
    # 确定配置文件路径
    if config_path is None:
        config_path = DEFAULT_CONFIG_PATH
    else:
        config_path = Path(config_path)
    
    config = DEFAULT_CONFIG.copy()
    
    # 如果配置文件存在，则加载并合并配置
    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                user_config = yaml.safe_load(f)
                if user_config:
                    deep_update(config, user_config)
            logger.info(f"已加载配置文件: {config_path}")
        except Exception as e:
            logger.warning(f"加载配置文件失败: {e}，将使用默认配置")
    else:
        logger.warning(f"配置文件不存在: {config_path}，将使用默认配置")
        
        # 创建默认配置文件
        try:
            os.makedirs(config_path.parent, exist_ok=True)
            with open(config_path, 'w', encoding='utf-8') as f:
                yaml.dump(DEFAULT_CONFIG, f, default_flow_style=False, allow_unicode=True)
            logger.info(f"已创建默认配置文件: {config_path}")
        except Exception as e:
            logger.warning(f"创建默认配置文件失败: {e}")
    
    return config

def deep_update(target: Dict, source: Dict) -> Dict:
    """
    深度更新字典
    
    Args:
        target: 目标字典
        source: 源字典
    
    Returns:
        更新后的字典
    """
    for key, value in source.items():
        if isinstance(value, dict) and key in target and isinstance(target[key], dict):
            deep_update(target[key], value)
        else:
            target[key] = value
    return target 
